package com.bstek.uflo.form.view.common.impl;

import java.util.Map;

import org.htmlparser.Node;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.Span;
import org.htmlparser.util.NodeList;
import org.springframework.util.StringUtils;

import com.bstek.dorado.common.event.DefaultClientEvent;
import com.bstek.dorado.view.View;
import com.bstek.dorado.view.widget.Component;
import com.bstek.dorado.view.widget.base.toolbar.Button;
import com.bstek.dorado.view.widget.base.toolbar.ToolBar;
import com.bstek.uflo.form.Constants;
import com.bstek.uflo.form.action.Action;
import com.bstek.uflo.form.model.TableDefinition;
import com.bstek.uflo.form.view.common.AbstractButtonBuilder;

/**
 * @author Jacky.gao
 * @since 2013年11月14日
 */
@org.springframework.stereotype.Component("com.bstek.uflo.form.view.common.impl.ToolbarBuilder")
public class ToolbarBuilder extends AbstractButtonBuilder {

	public boolean support(TagNode node) {
		if(node instanceof Div){
			Div div=(Div)node;
			String css=div.getAttribute("class");
			if(css!=null && (css.equals("uflotoolbar"))){
				return true;
			}
		}
		return false;
	}

	public void build(TagNode node, View view, Map<String, Component> map,Map<String,Boolean> mappingMap,TableDefinition table) {
		ToolBar toolbar=new ToolBar();
		String id=node.getAttribute("id");
		if(StringUtils.isEmpty(id))return;
		toolbar.setRenderOn("#"+id);
		if(map.containsKey(id)){
			return;
		}
		map.put(id, toolbar);
		toolbar.setId(id);
		view.addChild(toolbar);
		NodeList list=node.getChildren();
		for(int i=0;i<list.size();i++){
			Node cnode=list.elementAt(i);
			if(cnode instanceof Span){
				Span span=(Span)cnode;
				String css=span.getAttribute("class");
				if(css!=null && (css.equals("uflotoolbarbutton"))){
					Button button=buildButton(span,view,table);
					toolbar.addItem(button);
				}
			}
		}
	}
	private Button buildButton(Span span,View view,TableDefinition table){
		String actionStr=span.getAttribute("action");
		if(StringUtils.isEmpty(actionStr))return null;
		String id=span.getAttribute("id");
		if(StringUtils.isEmpty(id))return null;
		Action action=(Action)applicationContext.getBean(actionStr);
		action.onViewInit(view);
		Button button=new Button();
		button.setCaption(action.getName());
		button.setIcon(action.getIcon());
		button.setId(id);
		String script=action.getClickScript(Constants.UPDATE_ACTION);
		DefaultClientEvent event=new DefaultClientEvent();
		if(StringUtils.hasText(script)){
			StringBuffer sb=new StringBuffer();
			sb.append("var result=view.id(\""+Constants.DATASET+"\").getData().validate();if(result!='ok')return;\n");
			sb.append("view.id(\""+Constants.UPDATE_ACTION+"\").set(\"parameter\",{action:\""+actionStr+"\",buttonId:\""+id+"\"});\n");
			script=sb.toString()+script;
			event.setScript(script);
		}else{
			event.setScript(buildEventScript(view,action,actionStr,id));
		}
		button.addClientEventListener("onClick", event);
		return button;
	}
}
